#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "led.h"
#include "tftspi.h"
#include "usart.h"
#include "driver/uart.h" 
#include "dht11.h"

/**
 * @brief       程序入口
 * @param       无
 * @retval      无
 */
void app_main(void)
{
	esp_err_t ret;
    uint8_t err;
    uint8_t t = 0;
    uint8_t temperature;
    uint8_t humidity;
    char tx_buf[12];

    ret = nvs_flash_init(); /* 初始化NVS */

    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }

    led_init();             /* 初始化LED */
    usart_init(115200);
	err = dht11_init();
    uart_write_bytes(USART_UX, (const char*)&err, sizeof(err));   /* 写数据 */

     while (1)
    {
        if (dht11_read_data(&temperature, &humidity) == 0)   /* 读取成功 */
        {
            /* 构造形如 "T25 H67\r\n" 的 ASCII 字符串，仅使用 C 语法 */
            tx_buf[0]  = 'T';
            tx_buf[1]  = '0' + temperature / 10;
            tx_buf[2]  = '0' + temperature % 10;
            tx_buf[3]  = ' ';
            tx_buf[4]  = 'H';
            tx_buf[5]  = '0' + humidity / 10;
            tx_buf[6]  = '0' + humidity % 10;
            tx_buf[7]  = '\r';
            tx_buf[8]  = '\n';
            uart_write_bytes(USART_UX, tx_buf, 9);             /* 发送 9 字节 */
        }
        else
        {
            /* 错误提示 */
            const char *e = "DHT11_ERR\r\n";
            uart_write_bytes(USART_UX, e, 10);
        }

        LED_TOGGLE();
        vTaskDelay(pdMS_TO_TICKS(1000));   /* 1 秒周期 */
    }
}
